import { Button, Form, Input, Select, Table, Drawer, Tree } from 'antd';
import { SettingOutlined } from '@ant-design/icons'
import React, { useEffect, useState, useRef } from 'react';
import Styles from "./../../assets/styles/shoptype.module.less"
import AddshopType from "../../components/AddshopType.jsx"
import { serviceType, delShop, addShop, updateShop } from '../../apis/service'
import qs from "querystring"
import { json } from 'react-router-dom';

const { Option } = Select;

function TypeService() {


  const [form] = Form.useForm();
  const [, forceUpdate] = useState({});
  const [checkStrictly, setCheckStrictly] = useState(false);
  const [data, setData] = useState([])

  useEffect(() => {
    forceUpdate({});
    fetchData()
  }, [])

  const fetchData = async () => {
    const res = await serviceType()
    setData(res.data.rows.children)
  }

  //表格
  const columns = [

    {
      title: '名称',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      render: (a) => <a><div onClick={() => update(a)}><SettingOutlined></SettingOutlined></div></a>,
    },
  ];
  const [treeDatas, setTreeDatas] = useState([])
  const [allData, setAllData] = useState({})
  const [forms] = Form.useForm()

  //搜索输入框
  const onFinish = async (values) => {
    
    const h=qs.stringify(values)
    const res = await serviceType(h)
    setData(res.data.rows.children)
  }
  //修改
  const update = (a) => {
    // console.log(a)
    setOpen(true)
    setTreeDatas(data)
    setAllData(a)
    forms.setFieldsValue(a)
  }
  const onFinishs = async (values) => {
    const all = {
      name: values.title,
      parentId: allData.parentId,
      id: allData.id
    }

    const shops = qs.stringify(all)
    const res = await updateShop(shops)
    setOpen(false)
    fetchData()

  };

  //删除
  const [id, setID] = useState('')
  const rowSelection = {
    onChange: async (selectedRowKeys, selectedRows) => {
      // console.log('99', selectedRowKeys, selectedRows);
      setID(selectedRowKeys.join())

    },
    onSelect: (record, selected, selectedRows) => {
      // console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      // console.log(selected, selectedRows, changeRows);
    },
  };
  const delMsg = async () => {
    const res = await delShop(id)
    // console.log(res)
    fetchData()
  }

  //树状图
  const getTree = async (p) => {
    const shops = {
      name: p.shoptype,
      pid: p.password
    }
    const newShop = qs.stringify(shops)
    // console.log("00000000000", shops)
    const res = await addShop(newShop)
    // console.log(res)
    fetchData()
  }

  //修改模态框开关
  const [open, setOpen] = useState(false);
  //关闭模态框
  const onClose = () => {
    setOpen(false);
  };

  const onFinishFailed = (errorInfo) => {
    // console.log('Failed:', errorInfo);
  };
  //重置
  const clearForm = useRef()
  const resetting = () => {
    clearForm.current.resetFields()
  }
  return (
    <div>
      <div className={Styles.headerOne}>
        <Form form={form} name="horizontal_login" layout="inline" onFinish={onFinish} ref={clearForm}>
          <Form.Item
            name="name"
            label="商品类型名称:"
          >
            <Input placeholder="" />
          </Form.Item>
          <div className={Styles.findOne}>
            <Form.Item shouldUpdate>
              {() => (
                <Button type="primary" htmlType="submit" className={Styles.find}>
                  查询
                </Button>
              )}
            </Form.Item>
            <Button className={Styles.findTwo} onClick={resetting}>重置</Button>
          </div>

        </Form>
      </div>
      {/* 新增抽屉 */}
      <div style={{ display: "flex", flexDirection: "row" }}>
        <div><AddshopType treedata={data} getTree={getTree}></AddshopType></div>
        <div style={{ marginLeft: "20px" }} onClick={delMsg}><Button>删除</Button></div>
      </div>


      <div style={{ marginTop: "20px" }}>
        <Table
          columns={columns}
          rowSelection={{
            ...rowSelection,
            checkStrictly,
          }}
          dataSource={data}
          bordered
          rowKey="id"
          pagination={{
            pageSize: 10,
            pageSizeOptions: [5, 10, 15],
            showSizeChanger: true,
            showQuickJumper: true
          }}
          size="large"
        />
      </div>

      {/* 修改模态框 */}
      <div>
        <Drawer title="修改商品类型" placement="right" onClose={onClose} open={open}>
          <Form
            form={forms}
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={onFinishs}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="商品类型名称"
              name="title"
              rules={[
                {
                  required: true,
                  message: '请输入商品类型名称',
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="上级商品类型"
              name="password"
            >
              <Tree
                // checkStrictly
                disabled
                checkable
                defaultExpandedKeys={['']}
                defaultCheckedKeys={[allData.id]}
                // onCheck={onCheck}
                treeData={treeDatas}
              />
            </Form.Item>


            <Form.Item
              wrapperCol={{
                offset: 15,
                span: 9,
              }}
            >
              <div style={{ display: "flex", flexDirection: "row" }}>
                <Button style={{ marginRight: "10px" }}>取消</Button>
                <Button type="primary" htmlType="submit" style={{ marginRight: "10px" }}>
                  提交
                </Button>
              </div>

            </Form.Item>
          </Form>
        </Drawer>
      </div>
    </div>
  )
}

export default TypeService